package com.atguigu.gmall.order.listener;

import com.alibaba.fastjson.JSON;
import com.atguigu.gmall.common.config.rabbitMq.MqService;
import com.atguigu.gmall.enums.ProcessStatus;
import com.atguigu.gmall.mq.ware.WareStockResult;
import com.atguigu.gmall.order.biz.OrderBizService;
import com.rabbitmq.client.Channel;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.Exchange;
import org.springframework.amqp.rabbit.annotation.Queue;
import org.springframework.amqp.rabbit.annotation.QueueBinding;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.stereotype.Service;

import java.io.IOException;

/**
 * 订单库存的监听
 */
@Service
@Slf4j
public class OrderStockListener {
    @Autowired
    private OrderBizService  orderBizService;
    @Autowired
    private  MqService mqService;
    @RabbitListener(bindings = {@QueueBinding(value = @Queue(value = "queue.ware.order",
            durable ="true",
            exclusive = "false",
            autoDelete = "false"),
            exchange = @Exchange(value ="exchange.direct.ware.order",durable = "true",autoDelete = "false")
            ,key = "ware.order"
    )})
    public void listener(Message message, Channel channel) throws IOException {
        long tag = message.getMessageProperties().getDeliveryTag();
        String content = new String(message.getBody());
        try{
            WareStockResult result = JSON.parseObject(content, WareStockResult.class);
            log.info("监听到库存扣减结果",content);
            // TODO 修改订单状态
            orderBizService.updateOrderStockStatus(result);
            channel.basicAck(tag,false);
        }catch (Exception e){
            //消息发送失败重复五次
            mqService.retry(channel,tag,content,5);
        }




    }
}
